import { IconFont } from '@nutui/icons-react-taro'
import { Cell, TimeSelect } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import { useEffect, useState } from 'react'
import './index.less'

interface TimeType {
  value?: string
  text?: string
}

interface DateType {
  value?: string
  text?: string
  children?: TimeType[]
}

interface TimeSelectPickerProps {
  onChange?: (value: DateType) => void
  value?: DateType
  options?: DateType[]
}
const TimeSelectPicker = ({ onChange, value, options }: TimeSelectPickerProps) => {
  const [visible, setVisible] = useState(false)
  const [desc, setDesc] = useState('请选择预约时间')

  useEffect(() => {
    if (value) {
      const date = options?.find((item) => item.value === value.value)
      setDesc(`${date?.text} ${value.children?.[0]?.text}`)
    } else {
      setDesc('请选择预约时间')
    }
  }, [options, value])

  const handleClick = () => {
    setVisible(true)
  }
  const handleSelect = ([v]: DateType[]) => {
    setVisible(false)
    const date = options?.find((item) => item?.value === v?.value)
    if (date) {
      const _v = `${date?.text} ${v?.children?.[0]?.text}`
      setDesc(_v)

      if (onChange) {
        onChange({
          ...date,
          children: [
            {
              value: v?.children?.[0]?.value,
              text: v?.children?.[0]?.text,
            },
          ],
        })
      }
    }
  }
  const handleDateChange = (date: DateType, v: DateType[]) => {
    console.log(date, v)
  }
  const handleTimeChange = (time: TimeType, v: DateType[]) => {
    console.log(time, v)
  }
  return (
    <>
      <Cell
        title={
          <View className='cell-content'>
            <IconFont fontClassName='iconfont' classPrefix='icon' name='gerenzhongxin-zhihui' size={20} />
            <View className='cell-content-text'>
              <Text>{desc}</Text>
            </View>
          </View>
        }
        onClick={handleClick}
      />
      <TimeSelect
        visible={visible}
        multiple={false}
        options={options}
        onSelect={handleSelect}
        onDateChange={handleDateChange}
        onTimeChange={handleTimeChange}
      />
    </>
  )
}

export default TimeSelectPicker
